package com.wolf.gulimall.ware.listener;


import com.rabbitmq.client.Channel;
import com.wolf.common.to.mq.OrderTo;
import com.wolf.common.to.mq.StockLockedTo;
import com.wolf.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * rabbitmq 监听器
 */
@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 监听解锁库存
     * @param stockLockedTo 工作单信息
     * @param message mq消息
     * @param channel 信道
     * @throws IOException 异常
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存消息!!");
        try {
            wareSkuService.unLockStock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("解锁库存异常:",e);
            //库存解锁失败,将消息重新发到队列中,让消息可以再次进行消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 已关闭订单处理
     * @param order 订单信息
     * @param message mq消息
     * @param channel 信道
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo order, Message message, Channel channel) throws IOException {
        log.info("收到订单关闭解锁库存消息!!");
        try {
            wareSkuService.unLockStock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("订单关闭解锁库存异常:",e);
            //库存解锁失败,将消息重新发到队列中,让消息可以再次进行消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
